import React, { useMemo, useRef, useState, useEffect } from 'react';
import { Popconfirm, Spin } from 'antd';
import cn from 'classnames';
import { formatTime } from '@/pages/Recruitment/Interview/utils/utils';
import styles from '@/pages/Recruitment/Interview/Record.less';
import events from '@/utils/eventBus';
import EVENTBUS_TYPES from '@/pages/Recruitment/Interview/utils/EVENTBUS_TYPES';

const RecordTagButton = ({ params }) => {
    const { item, index, isRecord, classes, onQuestionRecord, loading } = params;
    const { id } = item;
    const userCode = useMemo(() => {
        const user = localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : {};
        return user?.userCode;
    }, []);
    const recTimmer = useRef(null); // 显示子录音时间长度
    const [subRecDuration, setSubRecDuration] = useState(0);
    const tipRef = useRef();
    const finishRef = useRef();
    const handleSetVisible = () => {
        localStorage.setItem(`interview_record_tag_${userCode}`, 'true');
    };

    /**
     *
     * @param {*} isStopAll 主录音停止、暂停时，触发录音片段全部暂停
     */
    const handleRecord = isStopAll => {
        if (!isRecord && !isStopAll) {
            console.log('阻止其它录音');
            events.emit(EVENTBUS_TYPES.STOP_OTHERS, id);
        }
        if (!isRecord) {
            // 开始标记录音片段
            recTimmer.current = setInterval(() => {
                setSubRecDuration(prev => prev + 1000);
            }, 1000);
        } else {
            // 停止标记录音片段
            clearInterval(recTimmer.current);
            setSubRecDuration(0);
        }
        const tag = localStorage.getItem(`interview_record_tag_${userCode}`);
        if (onQuestionRecord(item, index)) {
            if (!tag) {
                tipRef.current.setVisible(true);
                localStorage.setItem(`interview_record_tag_${userCode}`, 'true');
            }
        } else {
            clearInterval(recTimmer.current);
            recTimmer.current = null;
        }
    };
    useEffect(
        () => () => {
            if (recTimmer.current) {
                clearInterval(recTimmer.current);
            }
        },
        []
    );

    useEffect(() => {
        // 主录音停止、暂停时，触发录音片段暂停
        const eventDriveStop = () => {
            console.log('主录音停止、暂停时，触发录音片段暂停');
            if (isRecord) {
                handleRecord(true);
            }
        };
        /**
         * 处理问题录音片段标记互斥
         */
        const stopByOthers = questionId => {
            if (questionId !== id && isRecord) {
                console.log('处理问题录音片段标记互斥');
                handleRecord();
            }
        };
        events.addListener(EVENTBUS_TYPES.STOP_SUB_REC, eventDriveStop);
        events.addListener(EVENTBUS_TYPES.STOP_OTHERS, stopByOthers);
        return () => {
            events.removeListener(EVENTBUS_TYPES.STOP_SUB_REC, eventDriveStop);
            events.removeListener(EVENTBUS_TYPES.STOP_OTHERS, stopByOthers);
        };
    }, [isRecord]);
    return (
        <div style={{ position: 'relative' }}>
            <Popconfirm
                ref={tipRef}
                overlayClassName={styles.recordTagWrap}
                title="开始标记，再次点击完成标记，将自动生成录音文件"
                cancelText={null}
                okType="link"
                icon={null}
                okText="我知道了"
                getPopupContainer={trigger => trigger.parentNode}
                onConfirm={() => {
                    handleSetVisible();
                }}
            >
                <div style={{ position: 'absolute', top: 0, left: 0, width: '100%', height: '100%' }} />
            </Popconfirm>
            <Popconfirm
                ref={finishRef}
                title="完成录音标记？"
                getPopupContainer={trigger => trigger.parentNode}
                onConfirm={() => {
                    handleRecord();
                }}
                okText="完成"
                cancelText={null}
                overlayClassName={styles.recordHintWrap}
            >
                <div style={{ position: 'absolute', top: 0, left: 0, width: '100%', height: '100%' }} />
            </Popconfirm>
            <Spin spinning={!!loading}>
                <div
                    className={cn(styles.questionRecordButtonWrap, {
                        [styles.questionRecordButtonWrapHover]: !isRecord
                    })}
                    onClick={() => {
                        if (isRecord) {
                            finishRef.current.setVisible(true);
                            return;
                        }
                        handleRecord();
                    }}
                >
                    <div className={classes}>
                        <i className={`iconfont ${isRecord ? 'iconstop_record_Icon' : 'iconRecordMark_F'}`} />
                    </div>
                    {isRecord ? <span>{formatTime(subRecDuration)}</span> : '录音标记'}
                </div>
            </Spin>
        </div>
    );
};

export default React.memo(RecordTagButton);
